# -*- coding: utf-8 -*-
from dbobject import DBObject
from chemdb import dbHandle

class Reference(DBObject):

	def __init__(self, referenceId=-1):

		DBObject.__init__(self)

		self.id = referenceId

		#string
		self._things['author_name'] = ""
		self._things['year'] = ""
		self._things['name'] = ""
		self._things['source'] = ""

		print self.id


	def _getItem(self, name):
		if self.id == -1:
			return self._things[name]
		if name=="author_name":
			author = dbHandle.get('author_name', 'reference', 'id', self.id)
			self._things['author_name'] = author
			return author
		if name == "year":
			year = dbHandle.get('year', 'reference', 'id', self.id)
			self._things['year'] = year
			return year
		if name=="name":
			name = dbHandle.get('name', 'reference', 'id', self.id)
			self._things['name'] = name
			return name
		if name=="source":
			source = dbHandle.get('source', 'reference', 'id', self.id)
			self._things['source'] = source
			return source
		if name=="volume":
			volume = dbHandle.get('volume', 'reference', 'id', self.id)
			self._things['volume'] = volume
			return volume
		if name=="pages":
			pages = dbHandle.get('pages', 'reference', 'id', self.id)
			self._things['pages'] = pages
			return pages

	def insert(self):
		if self.id != -1:
			raise AttributeError, "Object already in DB"

		self.id = dbHandle.insertReference()

		for i in self._needToUpdate:
			self.updateDB(i)
		self._needToUpdate = []

	def updateDB(self, name):
		if self.id == -1:
			self._needToUpdate.append(name)
			return

		if name in self._things.keys():
			dbHandle.updateReference(self.id, name, self._things[name])
		else:
			raise NameError, name

def searchForReference(reference):

	query = {}
	if reference.name:
		query['name'] = reference.name
	if reference.source:
		query['source'] = reference.source
	if reference.author_name:
		query['author_name'] = reference.author_name
	if reference.volume:
		query['volume'] = reference.volume
	if reference.pages:
		query['pages'] = reference.pages

	ids = dbHandle.searchLike(query, 'reference')

	return [Reference(i[0]) for i in ids]